use crate::block::Block;

#[derive(Debug)]
pub struct BlockChain {
    pub blocks: Vec<Block>,
}

impl BlockChain {
    // 添加一个block
    pub fn add_block(&mut self, data: String) {
        let pre_hash = match self.blocks.last() {
            None => "".to_string(),
            Some(block) => block.hash.clone()
        };

        let block = Block::new_block(data, pre_hash);
        self.blocks.push(block);
    }

    // 初始的block
    fn new_genesis_block() -> Block {
        Block::new_block("This is genesis block".to_string(), String::from(""))
    }

    // 创建一个 chain
    pub fn new_block_chain() -> Self {
        let block = Self::new_genesis_block();
        let mut block_chain = Vec::new();
        block_chain.push(block);
        BlockChain {
            blocks: block_chain
        }
    }
}


#[cfg(test)]
mod test {
    use crate::blockchain::BlockChain;

    #[test]
    fn test() {
        let mut chain = BlockChain::new_block_chain();

        println!("chain is {:?}", chain);

        chain.add_block("A".to_string());
        println!("after push A , chain is {:?}", chain);

        chain.add_block("B".to_string());
        println!("after push B , chain is {:?}", chain);

        chain.add_block("C".to_string());
        println!("after push C , chain is {:?}", chain);
    }
}